/* Copyright 2009 Requirements Management System 
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.server;

import java.io.BufferedInputStream;
import java.net.URL;
import java.util.List;

import org.apache.commons.validator.GenericValidator;
import org.eclipse.core.runtime.Platform;
import org.eclipse.ui.internal.util.BundleUtility;
import org.mags.remas.app.Activator;
import org.mags.remas.logic.EntityFileUtils;
import org.mags.remas.model.entity.EntityFile;

/**
 * 
 * @author Mario Gaitan
 *
 */
@SuppressWarnings("restriction")
public class ImageUtils {
	public static byte[] getImageByPath(String pathInfo, StringBuffer ext) {
        byte[] data = null;    
        BufferedInputStream stream = null;
        try {
        	String[] path = pathInfo.split("/");
			if(path[1].equalsIgnoreCase("COMMONS")
				|| path[1].equalsIgnoreCase("ENTITY")
				|| path[1].equalsIgnoreCase("KEY")) {
		        if(path.length<3)
		        	throw new RuntimeException("invalid path"); 
		        URL url = BundleUtility.find(Platform.getBundle(Activator.PLUGIN_ID), "icons/"+path[1].toLowerCase()+"/"+path[2].toLowerCase());
		        stream = new BufferedInputStream(url.openStream());
		        data = new byte[stream.available()];
		        stream.read(data);
		        if(ext!=null)
		        	ext.append("png");
			} else {
		        if(path.length<2)
		        	throw new RuntimeException("invalid path");        
		        String id = path[1];
				if(GenericValidator.isBlankOrNull(id))
					throw new RuntimeException("document not found");        
				final long lId;
				try {
					lId = Long.parseLong(id);
				} catch(Exception e) {
					throw new RuntimeException("error in document id");
				}
				List<EntityFile> entityFiles = EntityFileUtils.getFiles(lId);
				if(entityFiles.size()>0) 
					data = entityFiles.get(0).getRawContent();
				if(ext!=null)
					ext.append("jpeg");
			}	
        } catch(Exception e) {
        	if(e instanceof RuntimeException)
        		throw (RuntimeException)e;
        	else
        		throw new RuntimeException(e);
        } finally {
        	try {
        		if(stream!=null)
        			stream.close();
        	}catch(Exception _e){/*IGNORE EXCEPTION*/}
        }
		return data;
	}
}
